<template>
  <div class="list">
    <ul>
      <li
        :ref="item"
        v-for="item of letters"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        @click="getChange"
      >
        {{item}}
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: 'ListAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null  // 函数节流
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },

  methods: {
    getChange (e) {
      const bar = e.target.innerText
      this.$emit('change', bar)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const endY = e.touches[0].clientY - 95
          const index = Math.floor((endY - this.startY) / 20)
          this.$emit('change', this.letters[index])
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>
<style scoped>
  .list {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top:95px;
    right: 0;
    bottom: 0;
    width: 20px;
    text-align: center;
  }
  .list ul li {
    line-height: 20px;
    font-size: 16px;

  }

</style>
